package com.webflux.demo.handler;

import com.webflux.demo.dao.UserDao;
import com.webflux.demo.modle.User;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * @Author RenPu
 * @Date 2023/5/23 16:01
 * @Version 1.0
 * @Description:
 **/

@Component
@AllArgsConstructor
public class UserHandler  {

    private final UserDao userDao;


    /**
     * 查询所有数据
     * @param serverRequest
     * @return
     */
    public  Mono<ServerResponse> listUser(ServerRequest serverRequest){
        Flux<User> userFlux = userDao.findAll();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(userFlux,User.class);

    }


    /**
     * 根据唯一id值进行查询数据
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> getById(ServerRequest serverRequest){

        Long id = Long.valueOf(serverRequest.pathVariable("id"));
        Mono<User> mono = userDao.findById(id);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(mono,User.class);

    }



    /**
     * 根据唯一id值进行删除数据
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> deleteById(ServerRequest serverRequest){

        Long id = Long.valueOf(serverRequest.pathVariable("id"));
        Mono<Void> mono = userDao.deleteById(id);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(mono,User.class);

    }


    /**
     * 保存数据
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> insert(ServerRequest serverRequest){
        Mono<User> userMono = serverRequest.bodyToMono(User.class);
        User user = userMono.block();
        return ServerResponse.ok().build(userDao.save(user).then());

    }






}
